import 'package:shared_preferences/shared_preferences.dart';
import 'package:synchronized/synchronized.dart';

class SpUtil {
  static SpUtil _singleton;
  static SharedPreferences _prefs;
  static Lock _lock = Lock();

  static Future<SpUtil> getInstance() async {
    if (_singleton == null) {
      await _lock.synchronized(() async {
        if (_singleton == null) {
          // 保持本地实例直到完全初始化。
          var singleton = SpUtil._();
          await singleton._init();
          _singleton = singleton;
        }
      });
    }
    return _singleton;
  }

  SpUtil._();

  Future _init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  static String getString(String key) {
    if (_prefs == null) return null;
    var status = _prefs.getString(key);
    if (status == null) return "";
    return status;
  }
  static Future<bool> putString(String key, String value) {
    if (_prefs == null) return null;
    return _prefs.setString(key, value);
  }

    // 保存数据
  static final String local_user_data =
      "local_user_data_"; //提交的资料信息  用于比较编辑资料时 是否修改资料 返回是否弹窗
  static final String local_circle_data =
      "local_circle_data_"; //提交的圈子信息  用于比较编辑圈子时 是否修改圈子 返回是否弹窗
  static final String user_data = "user_data_"; //保存的草稿信息

  static final String user_circle = "user_circle_"; //保存的圈子草稿信息

  static final String official_circle = "official_circle_"; //是否勾选官方圈子

  // 保存数据
  static Future setData(String key, value) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp.setString(key, value);
  }

  // 获取数据
  static Future<String> getData(String key) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    return sp.getString(key);
  }

  // 清除数据
  static Future clearData(String key) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp.remove(key);
  }
}
